//
//  SDRegisterViewController.swift
//  Seed
//
//  Created by Samuel on 2017/6/5.
//  Copyright © 2017年 RedSoft. All rights reserved.
//  手机注册（或微信登录绑定手机号）

import UIKit
import SVProgressHUD
import Alamofire
import SwiftyJSON

class SDRegisterViewController: YMBaseViewController {

    @IBOutlet weak var verifyBtn: UIButton!
    
    @IBOutlet weak var phoneField: UITextField!
    
    @IBOutlet weak var pwdField: UITextField!
    
    @IBOutlet weak var verifyField: UITextField!
    
    @IBOutlet weak var nextStepBtn: UIButton!
    
    var uid:String?
    var imgUrl:String?
    var nickName:String?
    
    private var index = 60
    private var timer: Timer?
    
    enum VcType {
        case PhoneRegister //手机注册
        case BindWechat //微信登录绑定手机号
    }
    
    var type = VcType.PhoneRegister
    
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
    }
    
    deinit {
        timer?.invalidate()
    }
    
    func configUI() {
        if type == .PhoneRegister {
            navigationItem.title = "手机注册"
        }else{
            navigationItem.title = "绑定手机号"
            nextStepBtn.setTitle("完成", for: .normal)
        }
        
        nextStepBtn.clipsToBounds = true
        nextStepBtn.layer.cornerRadius = 5.0
        
        verifyBtn.layer.borderWidth = 1
        verifyBtn.layer.borderColor = YMGlobalRedColor().cgColor
        verifyBtn.layer.cornerRadius = 5.0
        verifyBtn.clipsToBounds = true
    }
    
    @IBAction func getVerifyCode(_ sender: UIButton) {
        if !(phoneField.text! =~  RegexHelper.isIphoneNum){
            SVProgressHUD.showError(withStatus: "请输入正确的手机号")
            return
        }
        
        timer =  Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(tickDown), userInfo: nil, repeats: true)
        timer?.fire()
        verifyBtn.isEnabled = false
        verifyBtn.setTitle("\(index)s", for: .normal)
        
        SDNetworkTool.shared.getverifyCode(withPhoneNum: self.phoneField.text!, target: "register") {
            SVProgressHUD.showSuccess(withStatus: "验证码已发送")
        }
    }
    
    //完成绑定手机号
    @IBAction func nextStep(_ sender: UIButton) {
        if self.type == .BindWechat {
            if !(phoneField.text! =~  RegexHelper.isIphoneNum){
                SVProgressHUD.showError(withStatus: "手机号码格式错误")
                return
            }
            if ((pwdField.text?.characters.count)! < 6) || ((pwdField.text?.characters.count)! > 13){
                SVProgressHUD.showError(withStatus: "密码长度不满足要求")
                return
            }
            if (verifyField.text?.isEmpty)! {
                SVProgressHUD.showError(withStatus: "未输入验证码")
                return
            }
            SVProgressHUD.show(withStatus: "正在提交,请稍候...")
            
            SDNetworkTool.shared.register(withPhone: self.phoneField.text!, passwd: self.pwdField.text!, unionId: self.uid, smsCode: self.verifyField.text!, nickname: self.nickName!, headImage: self.imgUrl!, finished: { (account:SDAccount) in
                //注册成功，直接登录
                SVProgressHUD.showSuccess(withStatus: "完善信息成功")
                //保存当前账号信息
                SDAccountTool.shared.saveAccount(account)
                //保存登陆状态，跳转登陆
                appDelegate.setLoginStatus(true)
            })
        }
    }
    
    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
        if self.type == .PhoneRegister {
            if !(phoneField.text! =~  RegexHelper.isIphoneNum){
                SVProgressHUD.showError(withStatus: "手机号码格式错误")
                return false
            }
            if ((pwdField.text?.characters.count)! < 6) || ((pwdField.text?.characters.count)! > 13){
                SVProgressHUD.showError(withStatus: "密码长度不满足要求")
                return false
            }
            if (verifyField.text?.isEmpty)! {
                SVProgressHUD.showError(withStatus: "未输入验证码")
                return false
            }
            return true
        }else{
            return false
        }
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.destination is SDGetInfoViewController {
            let infoVc = segue.destination as! SDGetInfoViewController
            infoVc.phone = self.phoneField.text!
            infoVc.verifyCode = self.verifyField.text!
            infoVc.passwd = self.pwdField.text!
        }
    }
    
    func tickDown() {
        if index > 0 {
            index -= 1
            verifyBtn.setTitle("\(index)s", for: .normal)
        }else{
            timer?.invalidate()
            timer = nil
            index = 60
            verifyBtn.isEnabled = true
            verifyBtn.setTitle("获取", for: .normal)
        }
    }
}
